package com.example.highway.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.highway.config.MyJson;
import com.example.highway.dao.CarDao;
import com.example.highway.entity.Car;
import com.example.highway.entity.CarRecord;
import com.example.highway.entity.OwnerInspectorApeal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.domain.Example;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.List;
import java.util.Optional;

@RestController
@CrossOrigin
@RequestMapping("car")
public class CarController {
    @Autowired
    CarDao carDao;

    @RequestMapping("add")
    public MyJson info(@RequestBody() String msg){
        JSONObject jsonObject = JSON.parseObject(msg);
        Car car;
        try {
            car = carDao.save(jsonObject.toJavaObject(Car.class));
        } catch (Exception e){
            JSONObject rtn = new JSONObject();
            String errMsg = "duplicate value";
            rtn.put("msg", errMsg);
            return new MyJson("1", rtn);
        }

        JSONObject rtn = new JSONObject();
        rtn.put("id", car.getId());
        return new MyJson("0", rtn);
    }

    @RequestMapping("get")
    public MyJson one(@RequestBody() String msg){
        JSONObject jsonObject = JSON.parseObject(msg);

//        if(jsonObject.containsKey("id")){
//            Optional<Car> o = carDao.findById((Integer)jsonObject.get("id"));
//            if(!o.isPresent()){
//                return new MyJson("0", null);
//            }else {
//                Car Car = o.get();
//                return new MyJson("0", Car);
//            }
//        }

        Car car = jsonObject.toJavaObject(Car.class);

        List<Car> cars = carDao.findAll(Example.of(car));

        return new MyJson("0", JSONArray.toJSON(cars));
    }
//
//    @RequestMapping("get-all")
//    public MyJson all(){
//        List<Car> o = carDao.findAll();
//        if(o.isEmpty()){
//            return new MyJson("0", null);
//        }
//
//        return new MyJson("0", o);
//
//    }
}
